package dev.ece.util.io.tga;

import java.io.IOException;
import java.nio.ByteOrder;
import java.util.Locale;

import javax.imageio.ImageReader;
import javax.imageio.spi.ImageReaderSpi;
import javax.imageio.stream.ImageInputStream;

import dev.ece.util.io.tga.TGAImageReader.TGAHeader;

public class TGAImageReaderSpi extends ImageReaderSpi {

	private static final String vendorName = "Sneakxy";

    private static final String version = "1.0";

    private static final String[] names = { "tga", "TGA" };

    private static final String[] suffixes = { "tga" };

    private static final String[] MIMETypes = { "image/tga", "image/x-tga" };

    private static final String readerClassName =
        "dev.ece.util.io.tga.TGAImageReader";

//    private static final String[] writerSpiNames = {
//        "com.sun.imageio.plugins.png.PNGImageWriterSpi"
//    };

    public TGAImageReaderSpi() {
        super(vendorName,
              version,
              names,
              suffixes,
              MIMETypes,
              readerClassName,
              new Class[] { ImageInputStream.class },
              null,
              false,
              null, null,
              null, null,
              true,
              null,
              null,
              null, null
              );
    }
    
	@Override
	public boolean canDecodeInput(Object input) throws IOException {
		if (!(input instanceof ImageInputStream)) {
            return false;
        }
        ImageInputStream stream = (ImageInputStream) input;
        ByteOrder byteOrder = stream.getByteOrder();
        stream.setByteOrder(ByteOrder.LITTLE_ENDIAN);
        stream.mark();
        TGAHeader header = TGAHeader.readTGAHeader(stream);
        stream.reset();
        stream.setByteOrder(byteOrder);
		return (header.getImagetype() == 2 || header.getImagetype() == 10) 
				&& header.getWidth() > 0 
				&& header.getHeight() > 0
				&& (header.getBits() == 24 || header.getBits() == 32);
	}

	@Override
	public ImageReader createReaderInstance(Object extension) throws IOException {
		return new TGAImageReader(this);
	}

	@Override
	public String getDescription(Locale locale) {
		return "Standard TGA image reader";
	}

}
